home *** CD-ROM | disk | FTP | other *** search
/ Atari Mega Archive 1 / Atari Mega Archive - Volume 1.iso / gnu / bash / bash_108 / bash-108.zoo / bash-1.08 / expr.c.orig < prev    next >
Encoding:
Text File  |  1991-05-17  |  13.0 KB  |  605 lines

  1. /* expr.c -- arithmetic expression evaluation.
  2.  
  3.    Copyright (C) 1990, 1991 Free Software Foundation, Inc.
  4.  
  5.    This file is part of GNU Bash, the Bourne Again SHell.
  6.  
  7.    Bash is free software; you can redistribute it and/or modify it
  8.    under the terms of the GNU General Public License as published by
  9.    the Free Software Foundation; either version 1, or (at your option)
  10.    any later version.
  11.  
  12.    Bash is distributed in the hope that it will be useful, but WITHOUT
  13.    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  14.    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
  15.    License for more details.
  16.  
  17.    You should have received a copy of the GNU General Public License
  18.    along with Bash; see the file COPYING.  If not, write to the Free
  19.    Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  20.  
  21.  All arithmetic is done as long integers with no checking for overflow
  22.  (though division by 0 is caught and flagged as an error).
  23.  
  24.  The following operators are handled, grouped into a set of levels in
  25.  order of decreasing precedence.
  26.  
  27.     "-"            [level 0 (unary negation)]
  28.     "!"            [level 1]
  29.     "*", "/", "%"        [level 2]
  30.     "+", "-"        [level 3]
  31.     "<=", ">=", "<", ">"    [level 4]
  32.     "==", "!="        [level 5]
  33.     "="            [level 6 (assignment)]
  34.  
  35.  (Note that most of these operators have special meaning to bash, and an
  36.  entire expression should be quoted, e.g. "a=$a+1" or "a=a+1" to ensure
  37.  that it is passed intact to the evaluator when using `let'.  When using
  38.  the $[] form, the text between the `[' and `]' is treated as if in double
  39.  quotes.)
  40.  
  41.  Sub-expressions within parentheses have a precedence level greater than
  42.  all of the above levels and are evaluated first.  Within a single prece-
  43.  dence group, evaluation is left-to-right, except for the arithmetic
  44.  assignment operator (`='), which is evaluated right-to-left (as in C).
  45.  
  46.  The expression evaluator returns the value of the expression (assignment
  47.  statements have as a value what is returned by the RHS).  The `let'
  48.  builtin, on the other hand, returns 0 if the last expression evaluates to
  49.  a non-zero, and 1 otherwise.
  50.  
  51.  Implementation is a recursive-descent parser.
  52.  
  53.  Chet Ramey
  54.  chet@ins.CWRU.Edu
  55. */
  56.  
  57. #include <stdio.h>
  58. #include "shell.h"
  59.  
  60. #define variable_starter(c) (isletter(c) || (c == '_'))
  61. #define variable_character(c) (isletter(c) || (c == '_') || digit(c))
  62.  
  63. #if defined (NULL)
  64. #undef NULL
  65. #endif
  66. #define NULL 0
  67.  
  68. static char    *expression = (char *) NULL;    /* The current expression */
  69. static char    *tp = (char *) NULL;        /* token lexical position */
  70. static int    curtok = 0;            /* the current token */
  71. static int    lasttok = 0;            /* the previous token */
  72. static char    *tokstr = (char *) NULL;    /* current token string */
  73. static int    tokval = 0;            /* current token value */
  74. static jmp_buf    evalbuf;
  75.  
  76. static void    readtok();            /* lexical analyzer */
  77. static long    assignment(), exp0(), exp1(), exp2(), exp3(), exp4(), exp5();
  78. static long    strlong();
  79. static void    evalerror();
  80.  
  81. /*
  82.  * Because of the $[...] construct, expressions may include newlines.  This
  83.  * redefines `whitespace' so that a newline is added.
  84.  */
  85.  
  86. #ifdef whitespace
  87. #undef whitespace
  88. #endif
  89.  
  90. #define whitespace(c)    ((c) == ' ' || (c) == '\t' || (c) == '\n')
  91.  
  92. /* A structure defining a single expression context. */
  93. typedef struct {
  94.   int curtok, lasttok;
  95.   char *expression, *tp;
  96.   int tokval;
  97.   char *tokstr;
  98. } EXPR_CONTEXT;
  99.  
  100. /* Global var which contains the stack of expression contexts. */
  101. static EXPR_CONTEXT **expr_stack;
  102. static int expr_depth = 0;       /* Location in the stack. */
  103. static int expr_stack_size = 0;       /* Number of slots already allocated. */
  104.  
  105. /* Size be which the expression stack grows when neccessary. */
  106. #define EXPR_STACK_GROW_SIZE 10
  107.  
  108. /* Maximum amount of recursion allowed.  This prevents a non-integer
  109.    variable such as "num=num+2" from infinitely adding to itself when
  110.    "let num=num+2" is given.  I have to talk to Chet about this hack. */
  111. #define MAX_EXPR_RECURSION_LEVEL 1024
  112.  
  113. extern long atol ();
  114. extern char *itos (), *get_string_value (), *xmalloc ();
  115.  
  116. /* The Tokens.  Singing "The Lion Sleeps Tonight". */
  117.  
  118. #define EQEQ    1    /* "==" */
  119. #define NEQ    2    /* "!=" */
  120. #define LEQ    3    /* "<=" */
  121. #define GEQ    4    /* ">=" */
  122. #define STR    5    /* string */
  123. #define NUM    6    /* number */
  124. #define EQ    '='
  125. #define GT    '>'
  126. #define LT    '<'
  127. #define PLUS    '+'
  128. #define MINUS    '-'
  129. #define MUL    '*'
  130. #define DIV    '/'
  131. #define MOD    '%'
  132. #define NOT    '!'
  133. #define LPAR    '('
  134. #define RPAR    ')'
  135.  
  136. /* Push and save away the contents of the globals describing the
  137.    current expression context. */
  138. static void
  139. pushexp ()
  140. {
  141.   EXPR_CONTEXT *context;
  142.  
  143.   context = (EXPR_CONTEXT *)xmalloc (sizeof (EXPR_CONTEXT));
  144.  
  145.   if (expr_depth >= MAX_EXPR_RECURSION_LEVEL)
  146.     evalerror ("expression recursion level exceeded");
  147.  
  148.   if (expr_depth >= expr_stack_size)
  149.     {
  150.       expr_stack = (EXPR_CONTEXT **)
  151.     xrealloc (expr_stack, (expr_stack_size += EXPR_STACK_GROW_SIZE)
  152.           * sizeof (EXPR_CONTEXT *));
  153.     }
  154.  
  155.   context->curtok = curtok;
  156.   context->lasttok = lasttok;
  157.   context->expression = expression;
  158.   context->tp = tp;
  159.   context->tokval = tokval;
  160.   context->tokstr = tokstr;
  161.   expr_stack[expr_depth++] = context;
  162. }
  163.  
  164. /* Pop the the contents of the expression context stack into the
  165.    globals describing the current expression context. */
  166. static void
  167. popexp ()
  168. {
  169.   EXPR_CONTEXT *context;
  170.  
  171.   if (expr_depth == 0)
  172.     evalerror ("Recursion stack underflow");
  173.  
  174.   context = expr_stack[--expr_depth];
  175.   curtok = context->curtok;
  176.   lasttok = context->lasttok;
  177.   expression = context->expression;
  178.   tp = context->tp;
  179.   tokval = context->tokval;
  180.   tokstr = context->tokstr;
  181.   free (context);
  182. }
  183.  
  184. /* Evaluate EXPR, and return the arithmetic result.
  185.  
  186.    The `while' loop after the longjmp is caught relies on the above
  187.    implementation of pushexp and popexp leaving in expr_stack[0] the
  188.    values that the variables had when the program started.  That is,
  189.    the first things saved are the initial values of the variables that 
  190.    were assigned at program startup or by the compiler.  Therefore, it is
  191.    safe to let the loop terminate when expr_depth == 0, without freeing up
  192.    any of the expr_depth[0] stuff. */
  193. long
  194. evalexp (expr)
  195.      char *expr;
  196. {
  197.   long val = 0L;
  198.  
  199.   if (expr == NULL || *expr == NULL)
  200.     return (0);
  201.  
  202.   if (setjmp (evalbuf))
  203.     {
  204.       if (tokstr)        /* Clean up local allocation. */
  205.     free(tokstr);
  206.  
  207.       if (expression)
  208.     free (expression);
  209.  
  210.       while (--expr_depth)
  211.     {
  212.       if (expr_stack[expr_depth]->tokstr)
  213.         free (expr_stack[expr_depth]->tokstr);
  214.  
  215.       if (expr_stack[expr_depth]->expression)
  216.         free (expr_stack[expr_depth]->expression);
  217.     }
  218.       longjmp (top_level, DISCARD);
  219.     }
  220.  
  221.   pushexp ();
  222.   curtok = lasttok = 0;
  223.   expression = savestring (expr);
  224.   tp = expression;
  225.  
  226.   readtok ();
  227.  
  228.   val = assignment ();
  229.  
  230.   if (curtok != 0) 
  231.     evalerror ("syntax error in expression");
  232.  
  233.   if (expression)
  234.     free (expression);
  235.  
  236.   popexp ();
  237.   return (val);
  238. }
  239.  
  240. /* Bind/create a shell variable with the name LHS to the RHS.
  241.    This creates or modifies a variable such that it is an integer.
  242.  
  243.    This should really be in variables.c, but it is here so that all of the
  244.    expression evaluation stuff is localized.  Since we don't want any
  245.    recursive evaluation from bind_variable() (possible without this code,
  246.    since bind_variable() calls the evaluator for variables with the integer
  247.    attribute set), we temporarily turn off the integer attribute for each
  248.    variable we set here, then turn it back on after binding as necessary. */
  249.  
  250. void
  251. bind_int_variable (lhs, rhs)
  252.      char *lhs, *rhs;
  253. {
  254.   register SHELL_VAR *v;
  255.   int isint = 0;
  256.  
  257.   v = find_variable (lhs);
  258.   if (v)
  259.     {
  260.       isint = integer_p (v);
  261.       v->attributes &= ~att_integer;
  262.     }
  263.  
  264.   v = bind_variable (lhs, rhs);
  265.   if (isint)
  266.     v->attributes |= att_integer;
  267. }
  268.  
  269. static long
  270. assignment ()
  271. {
  272.   register long    val1, val2;
  273.   char *lhs;
  274.   char *rhs;
  275.  
  276.   val1 = val2 = exp5 ();
  277.   if (curtok == EQ)
  278.     {
  279.       if (lasttok != STR)
  280.     evalerror ("attempted assignment to non-variable");
  281.  
  282.       lhs = savestring (tokstr);
  283.       readtok ();
  284.       val2 = assignment ();
  285.       rhs = itos (val2);
  286.       bind_int_variable (lhs, rhs);
  287.       free (rhs);
  288.       free (lhs);
  289.       free (tokstr);
  290.       tokstr = (char *)NULL;        /* For freeing on errors. */
  291.     }
  292.   return (val2);
  293. }
  294.  
  295. static long
  296. exp5 ()
  297. {
  298.   register long val1, val2;
  299.  
  300.   val1 = exp4 ();
  301.  
  302.   while ((curtok == EQEQ) || (curtok == NEQ))
  303.     {
  304.       int op = curtok;
  305.  
  306.       readtok ();
  307.       val2 = exp4 ();
  308.       if (op == EQEQ)
  309.     val1 = val1 == val2;
  310.       else if (op == NEQ)
  311.     val1 = val1 != val2;
  312.     }
  313.   return (val1);
  314. }
  315.  
  316. static long
  317. exp4 ()
  318. {
  319.   register long val1, val2;
  320.  
  321.   val1 = exp3 ();
  322.   while ((curtok == LEQ) ||
  323.      (curtok == GEQ) ||
  324.      (curtok == LT) ||
  325.      (curtok == GT))
  326.     {
  327.       int op = curtok;
  328.  
  329.       readtok ();
  330.       val2 = exp3 ();
  331.  
  332.       if (op == LEQ)
  333.     val1 = val1 <= val2;
  334.       else if (op == GEQ)
  335.     val1 = val1 >= val2;
  336.       else if (op == LT)
  337.     val1 = val1 < val2;
  338.       else if (op == GT)
  339.     val1 = val1 > val2;
  340.     }
  341.   return (val1);
  342. }
  343.  
  344. static long
  345. exp3 ()
  346. {
  347.   register long val1, val2;
  348.  
  349.   val1 = exp2 ();
  350.  
  351.   while ((curtok == PLUS) || (curtok == MINUS))
  352.     {
  353.       int op = curtok;
  354.  
  355.       readtok ();
  356.       val2 = exp2 ();
  357.  
  358.       if (op == PLUS)
  359.     val1 += val2;
  360.       else if (op == MINUS)
  361.     val1 -= val2;
  362.     }
  363.   return (val1);
  364. }
  365.  
  366. static long
  367. exp2 ()
  368. {
  369.   register long val1, val2;
  370.  
  371.   val1 = exp1 ();
  372.  
  373.   while ((curtok == MUL) ||
  374.          (curtok == DIV) ||
  375.          (curtok == MOD))
  376.     {
  377.       int op = curtok;
  378.  
  379.       readtok ();
  380.  
  381.       val2 = exp1 ();
  382.  
  383.       if (((op == DIV) || (op == MOD)) && (val2 == 0))
  384.     evalerror ("division by 0");
  385.  
  386.       if (op == MUL)
  387.         val1 *= val2;
  388.       else if (op == DIV)
  389.         val1 /= val2;
  390.       else if (op == MOD)
  391.         val1 %= val2;
  392.     }
  393.   return (val1);
  394. }
  395.  
  396. static long
  397. exp1 ()
  398. {
  399.   register long val;
  400.  
  401.   if (curtok == NOT)
  402.     {
  403.       readtok ();
  404.       val = !exp0 ();
  405.     }
  406.   else
  407.     val = exp0 ();
  408.  
  409.   return (val);
  410. }
  411.  
  412. static long
  413. exp0 ()
  414. {
  415.   register long val = 0L;
  416.  
  417.   if (curtok == MINUS)
  418.     {
  419.       readtok ();
  420.       val = - exp0 ();
  421.     }
  422.   else if (curtok == LPAR)
  423.     {
  424.       readtok ();
  425.       val = assignment ();
  426.  
  427.       if (curtok != RPAR)
  428.     evalerror ("missing `)'");
  429.  
  430.       /* Skip over closing paren. */
  431.       readtok ();
  432.  
  433.     }
  434.   else if ((curtok == NUM) || (curtok == STR))
  435.     {
  436.       val = tokval;
  437.       readtok ();
  438.     }
  439.   else
  440.     evalerror ("syntax error in expression");
  441.  
  442.   return (val);
  443. }
  444.  
  445. /* Lexical analyzer/token reader for the expression evaluator.    Reads the
  446.    next token and puts its value into curtok, while advancing past it.
  447.    Updates value of tp.  May also set tokval (for number) or tokstr (for
  448.    string). */
  449. static void
  450. readtok ()
  451. {
  452.   register char *cp = tp;
  453.   register int c, c1;
  454.  
  455.   /* Skip leading whitespace. */
  456.   c = 0;
  457.   while (cp && (c = *cp) && (whitespace(c)))
  458.     cp++;
  459.  
  460.   if (c)
  461.     cp++;
  462.     
  463.   tp = cp - 1;
  464.  
  465.   if (c == '\0')
  466.     {
  467.       lasttok = curtok;
  468.       curtok = 0;
  469.       tp = cp;
  470.       return;
  471.     }
  472.  
  473.   if (variable_starter (c))
  474.     {
  475.       /* Semi-bogus K*rn shell compatibility feature -- variable
  476.      names not preceded with a dollar sign are shell variables. */
  477.       char *value;
  478.  
  479.       while (variable_character (c))
  480.     c = *cp++;
  481.  
  482.       c = *--cp;
  483.       *cp = '\0';
  484.  
  485.       tokstr = savestring (tp);
  486.       value = get_string_value (tokstr);
  487.  
  488.       if (value && *value)
  489.     tokval = evalexp (value);
  490.       else
  491.     tokval = 0;
  492.  
  493.       *cp = c;
  494.       lasttok = curtok;
  495.       curtok = STR;
  496.     }
  497.   else if (digit(c))
  498.     {
  499.       while (digit (c) || isletter (c) || c == '#')
  500.     c = *cp++;
  501.  
  502.       c = *--cp;
  503.       *cp = '\0';
  504.  
  505.       tokval = strlong (tp);
  506.       *cp = c;
  507.       lasttok = curtok;
  508.       curtok = NUM;
  509.  
  510.     }
  511.   else
  512.     {
  513.       c1 = *cp++;
  514.       if ((c == EQ) && (c1 == EQ)) 
  515.     c = EQEQ;
  516.       else if ((c == NOT) && (c1 == EQ))
  517.     c = NEQ;
  518.       else if ((c == GT) && (c1 == EQ))
  519.     c = GEQ;
  520.       else if ((c == LT) && (c1 == EQ))
  521.     c = LEQ;
  522.       else
  523.     cp--;            /* `unget' the character */
  524.       lasttok = curtok;
  525.       curtok = c;
  526.     }
  527.   tp = cp;
  528. }
  529.  
  530. static void
  531. evalerror (msg)
  532.      char *msg;
  533. {
  534.   builtin_error ("%s: %s (remainder of expression is \"%s\")",
  535.          expression, msg, (tp && *tp) ? tp : "");
  536.   longjmp (evalbuf, 1);
  537. }
  538.  
  539. /* Convert a string to a long integer, with an arbitrary base.
  540.    0nnn -> base 8
  541.    0xnn -> base 16
  542.    Anything else: [base#]number (this is from the ISO Pascal spec). */
  543. static long
  544. strlong (num)
  545.      char *num;
  546. {
  547.   register char *s = num;
  548.   register int c;
  549.   int base = 10;
  550.   long val = 0L;
  551.  
  552.   if (s == NULL || *s == NULL)
  553.     return 0L;
  554.  
  555.   if (*s == '0')
  556.     {
  557.       s++;
  558.  
  559.       if (s == NULL || *s == NULL)
  560.     return 0L;
  561.       
  562.        /* Base 16? */
  563.       if (*s == 'x' || *s == 'X')
  564.     {
  565.       base = 16;
  566.       s++;
  567.     }
  568.       else
  569.     base = 8;
  570.     }
  571.  
  572.   for (c = *s++; c; c = *s++)
  573.     {
  574.       if (c == '#')
  575.     {
  576.       base = (int)val;
  577.  
  578.       /* Illegal base specifications are silently reset to base 10.
  579.          I don't think that this is a good idea? */
  580.       if (base < 2 || base > 36)
  581.         base = 10;
  582.  
  583.       val = 0L;
  584.     }
  585.       else
  586.     if (isletter(c) || digit(c))
  587.       {
  588.         if (digit(c))
  589.           c = digit_value(c);
  590.         else if (c >= 'a' && c <= 'z')
  591.           c -= 'a' - 10;
  592.         else if (c >= 'A' && c <= 'Z')
  593.           c -= 'A' - 10;
  594.  
  595.         if (c >= base)
  596.           evalerror ("value too great for base");
  597.  
  598.         val = (val * base) + c;
  599.       }
  600.     else
  601.       break;
  602.     }
  603.   return (val);
  604. }
  605.